/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.wx.server.handler;

import cn.ac.iie.di.commons.httpserver.framework.handler.HandlerI;
import cn.ac.iie.di.commons.httpserver.framework.util.ParseRequestStream;
import cn.ac.iie.di.wx.server.common.RuntimeEnv;
import static cn.ac.iie.di.wx.server.handler.QueryFriendCircleMsgHandler.logger;
import cn.ac.iie.di.wx.server.httpservice.HttpSender;
import cn.ac.iie.di.wx.server.vo.RedisVo;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.eclipse.jetty.server.Request;

/**
 *
 * @author Administrator
 */
public class AddUnicontrolHandler implements HandlerI {

    static Logger logger = Logger.getLogger(AddUnicontrolHandler.class.getName());

    @Override
    public void init() throws Exception {
//        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public void execute(Request pRequest, HttpServletRequest request, HttpServletResponse response) throws Exception {
        String addUTMonitor = ParseRequestStream.parseRequestStreamAsString(pRequest.getInputStream());
        logger.info("AddUnicontrol request:" + addUTMonitor);

        try {
            JSONObject addUTMonitorJson = JSONObject.parseObject(addUTMonitor);
            String opid = addUTMonitorJson.getString("opid");//存redis里，将关键字存value里面
            //redis存key=pyq_opid,value=useridValue
            String useridValue = "";
            JSONArray param = addUTMonitorJson.getJSONArray("param");
            for (int i = 0; i < param.size(); i++) {
                JSONObject obi = param.getJSONObject(i);
                if (obi.getString("name").equals("userid")) {
                    useridValue = obi.getString("value");
                    System.out.println(useridValue);
                }
            }
            if (!useridValue.equals("") || useridValue != null) {
                RuntimeEnv.redisVos.put(new RedisVo("bcp_" + opid, useridValue));
                logger.info("put into redisVos queue,key = \"bcp_\"" + opid + ",value = " + useridValue);
            } else {
                logger.info("userid is null in this request");
            }            //将系统参数补全
            addUTMonitorJson.put("areaid", (String) RuntimeEnv.getParam(RuntimeEnv.areaid));
            addUTMonitorJson.put("userareaid", (String) RuntimeEnv.getParam(RuntimeEnv.userareaid));
            addUTMonitorJson.put("sysid", (String) RuntimeEnv.getParam(RuntimeEnv.sysid));
            addUTMonitorJson.put("sysuserid", (String) RuntimeEnv.getParam(RuntimeEnv.sysuserid));
            logger.info(addUTMonitorJson.toJSONString());
//            RuntimeEnv.redisVos.put(new RedisVo(opid, param));

            //获取响应,post，请求格式和发送方法
            HttpSender hs = new HttpSender();
            String responseStr = hs.closableHttpClient(addUTMonitorJson.toJSONString(), (String) RuntimeEnv.getParam(RuntimeEnv.addUnicontrol));
            //若frontnum=0，则表示请求已经处理完成，可以调用响应的接口进行ftp下载文件，文件存放在龙存
//        String responseStr = "{\"opid\": \"020005\",\"msgid\": \"123456\",\"frontnum\": 0,\"status\": \"200\"}";
            //解析响应
            if (responseStr.equals("")) {
                logger.info("AddUnicontrol response is null");
                responseStr = "{\"opid\": \"" + opid + "\",\"desc\": \"err烽火超时异常\",\"frontnum\": -1,\"status\": \"404\"}";;
            } else {
                logger.info("AddUnicontrol response is sucess:" + responseStr);

                try {

                    JSONObject jSONObject = JSONObject.parseObject(responseStr);
                    String frontnum = jSONObject.getString("frontnum");
                    String status = jSONObject.getString("status");
                    if (status.equals("200")) {
                        //状态正常
                        if (frontnum.equals("0")) {
                            logger.info("AddUnicontrol response is 200");
                        } else {
                            logger.info("AddUnicontrol该布控号正在排队中");
                        }
                    } else {
                        logger.info("AddUnicontrol请求状态不正常");
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage(), e);
                }
            }
            //给客户端发送响应消息
            byte[] bytesContent = new byte[1024 * 2];
            int bytesReadIn = 0;
            ServletOutputStream out = response.getOutputStream();
            BufferedOutputStream bos = new BufferedOutputStream(out);
            InputStream inputStream = new ByteArrayInputStream(responseStr.getBytes("UTF-8"));
            while ((bytesReadIn = inputStream.read(bytesContent, 0, 1024 * 2)) > 0) {
                bos.write(bytesContent, 0, bytesReadIn);
            }
            RuntimeEnv.addUNCTCount.getAndIncrement();
            bos.flush();
            bos.close();
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
    }

}
